package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.BaseFrom;
import com.moss.cloud.base.api.model.from.ConfigFrom;
import com.moss.cloud.base.api.model.from.SystemConfigFrom;
import com.moss.cloud.base.api.model.param.ConfigParam;
import com.moss.cloud.base.api.model.param.SystemConfigParam;
import com.moss.cloud.base.biz.mapper.SystemConfigMapper;
import com.moss.cloud.base.biz.service.ISystemConfigService;
import com.moss.cloud.common.base.model.po.SystemConfig;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.enums.state.Deleted;
import com.moss.cloud.common.core.exception.BaseException;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.AESUtil;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.security.component.RedisTemplateOps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 系统配置服务实现
 *
 * @author 瑾年
 * @date 2023年3月23日
 */
@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements ISystemConfigService {

    private final RedisTemplateOps redisTemplateOps;

    public SystemConfigServiceImpl(RedisTemplateOps redisTemplateOps) {
        this.redisTemplateOps = redisTemplateOps;
    }

    /**
     * 通过配置KEY查询配置值
     *
     * @param key
     * @return
     */
    @Override
    public SystemConfig getSystemConfig(String key) {
        SystemConfig systemConfig;
        Boolean hasKey = redisTemplateOps.hasKey(Constant.SYSTEM_CONFIG + key);
        if (hasKey.equals(Boolean.TRUE)) {
            systemConfig = (SystemConfig) redisTemplateOps.get(Constant.SYSTEM_CONFIG + key);
        } else {
            systemConfig = this.getOne(new QueryWrapper<SystemConfig>().lambda().eq(SystemConfig::getConfigCode, key));
            redisTemplateOps.set(Constant.SYSTEM_CONFIG + key, systemConfig);
        }
        return systemConfig;
    }

    /**
     * 加载系统配置
     */
    @Override
    public void loadSystemConfig() {
        List<SystemConfig> systemConfigs = this.list(new QueryWrapper<>());
        if (CollectionUtils.isEmpty(systemConfigs)) {
            throw new BaseException();
        }
        systemConfigs.forEach(item -> redisTemplateOps.set(Constant.SYSTEM_CONFIG + item.getConfigCode(), item));
    }

    /**
     * 系统参数列表
     *
     * @param systemConfigParam
     * @return
     */
    @Override
    public IPage<SystemConfig> getConfigs(SystemConfigParam systemConfigParam) {
        IPage<SystemConfig> systemConfigPage = new Page<>(systemConfigParam.getCurrent(),systemConfigParam.getSize());
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(SystemConfig::getDeleted, Deleted.DELETE.code())
                .eq(StringUtils.isNotBlank(systemConfigParam.getConfigCode()), SystemConfig::getConfigCode, systemConfigParam.getConfigCode())
                .like(StringUtils.isNotBlank(systemConfigParam.getConfigExplain()), SystemConfig::getConfigExplain, systemConfigParam.getConfigExplain())
                .eq(Objects.nonNull(systemConfigParam.getDeleted()), SystemConfig::getDeleted, systemConfigParam.getDeleted());
        return this.page(systemConfigPage, queryWrapper);
    }

    /**
     * 新增或修改配置
     *
     * @param systemConfigFrom
     * @return
     */
    @Override
    public Long saveOrUpdate(SystemConfigFrom systemConfigFrom) {
        BooleanHandel.isTrue(Objects.nonNull(systemConfigFrom.getId())).trueHandle(() -> {
            SystemConfig config = this.getById(systemConfigFrom.getId());
            BooleanHandel.trueThrow(Objects.isNull(config)).throwMessage(SystemErrorType.DATE_EMPTY);
        });
        SystemConfig systemConfig = new SystemConfig();
        BeanUtils.copyProperties(systemConfigFrom, systemConfig);
        boolean flag = Objects.nonNull(systemConfigFrom.getId()) ? this.updateById(systemConfig) :
                this.save(systemConfig);
        return flag ? systemConfig.getId() : 0L;
    }

    /**
     * 删除系统参数配置
     *
     * @param baseFrom
     * @return
     */
    @Override
    public Long delete(BaseFrom baseFrom) {
        BooleanHandel.isTrue(Objects.nonNull(baseFrom.getId())).trueHandle(() -> {
            SystemConfig config = this.getById(baseFrom.getId());
            BooleanHandel.trueThrow(Objects.isNull(config)).throwMessage(SystemErrorType.DATE_EMPTY);
        });
        boolean flag = this.removeById(baseFrom.getId());
        return flag ? baseFrom.getId() : 0L;
    }

    /**
     * 更新配置值
     *
     * @param configFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateValue(ConfigFrom configFrom){
        SystemConfig systemConfig = new SystemConfig();
        BeanUtils.copyProperties(configFrom,systemConfig);
        return this.updateById(systemConfig);
    }

    /**
     * 查看密码
     *
     * @param configParam
     * @return
     */
    @Override
    @SneakyThrows
    public String showPassword(ConfigParam configParam){
        BooleanHandel.trueThrow(!configParam.getConfigCode().equals(Constant.DEFAULT_PASSWORD))
                .throwMessage(SystemErrorType.QUERY_PARAM_ERROR);
        SystemConfig systemConfig = this.getById(configParam.getId());
        BooleanHandel.trueThrow(Objects.isNull(systemConfig)).throwMessage(SystemErrorType.DATE_EMPTY);
        return AESUtil.aesDecrypt(systemConfig.getConfigValue(), Constant.KEY);
    }
}
